using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
using Random = Unity.Mathematics.Random;

namespace Game.Core
{
    public unsafe partial struct AttackTargetJob : IJobEntity
    {
        // public EntityCommandBuffer.ParallelWriter ECBParallelWriter;
        
        [ReadOnly] public ComponentLookup<LocalTransform> Positions;
        [ReadOnly] public ComponentLookup<Damageable> Damageables;
        public BufferLookup<PropertyModifier> PropertyModifiers;
        
        void Execute(Entity entity, [EntityIndexInQuery]int index, ref Attackable attackable)
        {
            Random random = Random.CreateFromIndex((uint)index);
            if (Entity.Null != attackable.Target)
            {
                var attackerPos = Positions[entity].Position;
                var defenderPos = Positions[attackable.Target].Position;
                var distance = math.distance(attackerPos, defenderPos);
                

                if (distance <= attackable.Detail.AttackRange)
                {
                    Debug.Log($"Entity[{index}] Execute AttackTargetJob");

                    var propertyModifier = new PropertyModifier()
                    {
                        Property = new Property()
                        {
                            Source = PropertySource.Character,
                            Type = PropertyType.CurHealthPoint,
                            Value = -1,
                        },
                    };

                    var propertyModifiers = PropertyModifiers[attackable.Target];
                    propertyModifiers.Add(propertyModifier);

                    // var buffer = ECBParallelWriter.AddBuffer<PropertyModifier>(index, attackable.Target);
                    // buffer.Add(propertyModifier);
                }
            }
        }
    }
}